package com.zjitc.book.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import com.zjitc.book.common.result.R;
import com.zjitc.book.dto.UserDto;
import com.zjitc.book.entity.MyUserDetails;
import com.zjitc.book.entity.Permissions;
import com.zjitc.book.service.UserInfoService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@CrossOrigin
@RestController
@RequestMapping("/api")
public class UserController {

    private static final String key = "1234567890abcdef";
    @Autowired
    AuthenticationManager authManager;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserInfoService userInfoService;

    @PostMapping("/auth/login")
    public R<Map<String, Object>> login(@RequestBody UserDto user){//Entity和DTO的区别
        System.out.println(user);
        //1、借助authManager来完成认证
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authManager.authenticate(auth);

        //2、从authentication中获取用户信息
        MyUserDetails userDetails = (MyUserDetails)authentication.getPrincipal();
        Integer userId = userDetails.getUser().getId();
        String userName = userDetails.getUser().getUsername();
        List<String> authorities = userDetails.getAuthors();

        //2.1、把登录的用户权限存入redis
        stringRedisTemplate.opsForSet().add("user:perms:"+userId, authorities.toArray(new String[0]));

        //3、用hutool工具类生成JWT令牌（token）
        Map<String, Object> map = new HashMap<>();
        map.put("userid",userId);
        map.put("username",userName);
        map.put("exp", DateUtil.currentSeconds()+60*60);//过期时间
        String token = JWTUtil.createToken(map, key.getBytes());

        //4、返回响应
        Map<String, Object> res = new HashMap<>();
        res.put("token",token);
        res.put("userid", userId);
        res.put("username", userName);
        return R.success(res);


    }

    @GetMapping("/user/menu")
    public List<Permissions> getMenu(){
        List<Permissions> menu = userInfoService.getMenu();
        return menu;
    }
}
